import React, { useState, useEffect, useRef, Suspense } from 'react'


// https://www.bilibili.com/video/BV1qU4y1S7d4/
// context file
// React.createContext()里的内容只是为了在组件引用context的时候有下图这样的输入自动联想，不是实际的函数。不需要的话也可以空着
const AuthContext = React.createContext({
    token: null,
    userInfo: null,
    isLoggedIn: false,

    onLogin: (token, expTime) => {
        
    },
    onLogout: () => { },
})




export const AuthContextProvider = (props) => {
    

    const [token, setToken] = useState(() => {
        return localStorage.getItem("token")
    })

    const [userInfo, setUserInfo] = useState(() => {
        let user_info = localStorage.getItem("user_info")
        return user_info ? JSON.parse(user_info) : null
    })

    const [isLoggedIn, setLogggedIn] = useState(() => {
        return token != null && token != undefined
    })


    const onLogin = () => {
        // 这里写真正的登录方法
        console.log(`AuthContextProvider... run...`)

        setTimeout(() => {
            setToken("echo_token")
            localStorage.setItem("token", "echo_token")

            let user_info = {
                name: "echo",
                avator: "xxxxxx"
            }
            setUserInfo(user_info)
            localStorage.setItem("user_info", JSON.stringify(user_info))

            setLogggedIn(true)
        }, 2000)
    }


    const onLogout = () => {
        // 这里写真正的登出方法

        setTimeout(() => {
            localStorage.removeItem("token")
            localStorage.removeItem("user_info")


            setToken(null)
            setUserInfo(null)
            setLogggedIn(false)
        }, 2000)
    }



    return (
        <AuthContext.Provider value={{token, userInfo, isLoggedIn, onLogin, onLogout}}>
            {props.children}
        </AuthContext.Provider>
    )
}

export default AuthContext
